//
//  AVPlayerViewController.m
//  SuiRan
//
//  Created by lanou3g on 15-5-1.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "AVPlayerViewController.h"
#import "AudioStreamer.h"
#import "AudioPlayer.h"
#import "AFHTTPRequestOperationManager.h"
#import "playInfo.h"
#import "UIImageView+WebCache.h"
#import "RadioDetail.h"

@interface AVPlayerViewController ()
@property (nonatomic, retain) playInfo *p;
@property (nonatomic, assign) UIButton *button;
@property (nonatomic, assign) UILabel *playerLabel;
@property (nonatomic, assign) UIView *volumeSlider;
@property (nonatomic, assign) UILabel *positionLabelLeft;
@property (nonatomic, assign) UILabel *positionLabelRight;
@property (nonatomic, assign) UISlider *progressSlider;
@property (nonatomic, assign) NSTimer *progressUpdateTimer;
@property (nonatomic, retain) NSString *currentImageName;
@property (nonatomic, assign)  AudioStreamer *streamer;

@property (nonatomic, assign) UIAlertView *alertView;


@property (nonatomic, assign) UIImageView *bjtImage;
@property (nonatomic, retain) NSString *escapedValue;

@property (nonatomic, assign)UIButton *buttonX;

@property (nonatomic, assign)BOOL flag;


@end

@implementation AVPlayerViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    [self JsonData];
    
    
    
}

#pragma mark - 数据解析
- (void)JsonData
{
    self.p = [[playInfo new] autorelease];
    __block typeof(self) weakSelf = self;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *params = @{@"tingid" : _tingid2};
    [manager POST:kRadioDetailList parameters:params success:
     
     ^(AFHTTPRequestOperation *operation, id responseObject) {
         NSData *data = operation.responseData;
         NSDictionary *dict = [NSJSONSerialization  JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         
         
         NSDictionary *item = dict[@"data"][@"playInfo"];
         [weakSelf.p setValuesForKeysWithDictionary:item];
         
         
         [weakSelf loadData];
         [self CreateButton];
         [self createSliderPositionLeft];
         [self createSliderPositionRight];
         [self setButtonImageNamed:@"playbutton.png"];
         [self CreatedownloadSourceField];
         [self createStreamer];
         [self Monitor:_progressSlider];
         [self createTitle];
     //设置锁屏仍能继续播放   
         [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
         [[AVAudioSession sharedInstance] setActive: YES error: nil];
         
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              
              NSLog(@"下载错误 is %@",error);
              
          }];
    
}

- (void)loadData
{
    
    // 设置旋转按钮
    _buttonX = [UIButton buttonWithType:UIButtonTypeSystem];
    _buttonX.backgroundColor = [UIColor blackColor];
    _buttonX.frame = CGRectMake(0, 0, kScreenWidth / 3.0 * 2, kScreenWidth / 3.0 * 2);
    _buttonX.layer.cornerRadius = kScreenWidth / 3;
    _buttonX.center = CGPointMake(kScreenWidth/2.0, kScreenHeight/3.0);
    [self.view addSubview:_buttonX];
    
    
    
    
    
    //旋转图片
    [AudioPlayer ShowInstance].XZimageView = [[[UIImageView alloc] initWithFrame:_buttonX.bounds] autorelease];
    [AudioPlayer ShowInstance].XZimageView.layer.cornerRadius = kScreenWidth / 3;
    [AudioPlayer ShowInstance].XZimageView.layer.masksToBounds = YES;
    [[AudioPlayer ShowInstance].XZimageView sd_setImageWithURL:[NSURL URLWithString:_p.imgUrl]];
    [_buttonX addTarget:self action:@selector(buttonActionX:) forControlEvents:UIControlEventTouchUpInside];
    [_buttonX addSubview: [AudioPlayer ShowInstance].XZimageView];
    
    //创建滑动条
    UIImage *controlButton = [UIImage imageNamed:@"silder"];
    
    
    _progressSlider = [[[UISlider alloc] initWithFrame:CGRectMake(85. / 375 * kScreenWidth, kScreenHeight - 200 / 667.0 * kScreenHeight, 204.0 / 375 * kScreenWidth, 23.0 / 667.0 * kScreenHeight)] autorelease];
    _progressSlider.minimumValue = 1;
    _progressSlider.maximumValue = 100;
    [_progressSlider setThumbImage:controlButton forState:UIControlStateHighlighted];
    [_progressSlider setThumbImage:controlButton forState:UIControlStateNormal];
    _progressSlider.backgroundColor = [UIColor clearColor];
    
    // 设置划过区域颜色
    _progressSlider.minimumTrackTintColor=[UIColor colorWithRed:0.097 green:0.106 blue:0.305 alpha:1.000];
    [_progressSlider addTarget:self action:@selector(Monitor:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_progressSlider];
    
    //    //设置底部图片
    //    UIImageView *bottomPic = [[[UIImageView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 80.0 / 667 * kScreenHeight, kScreenWidth, 15.0 / 667 * kScreenHeight)] autorelease];
    //    bottomPic.image = [UIImage imageNamed:@"bottomPic"];
    //    [self.view addSubview:bottomPic];
    
}

// 创建标题
- (void)createTitle
{
    self.playerLabel = [[[UILabel alloc] initWithFrame:CGRectMake(37.5 / 375 * kScreenWidth, kScreenHeight - 280 / 667.0 * kScreenHeight, 300. / 375 * kScreenWidth, 50. / 667.0 * kScreenHeight)] autorelease];
    _playerLabel.text = _playerTitle;
    _playerLabel.numberOfLines = 0;
    _playerLabel.textAlignment = NSTextAlignmentCenter;
    
//    NSLog(@"%@", _playerLabel.text);
    _playerLabel.textColor = [UIColor colorWithRed:0.205 green:0.254 blue:0.415 alpha:1.000];
    _playerLabel.font = [UIFont fontWithName:@"Optima" size:20];
    [self.view addSubview:_playerLabel];
    
}

#pragma mark 旋转按钮方法
- (void)buttonActionX:(UIButton *)button
{
    CABasicAnimation *basic11 = [[CABasicAnimation new] autorelease];
    basic11 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    basic11.fromValue = @(0);
    basic11.toValue = @(M_PI*2);
    basic11.duration = 30;
    basic11.repeatCount = NSIntegerMax;
    [button.layer addAnimation:basic11 forKey:@"rotate"];
}

//滑动条的方法
- (void)Monitor:(UISlider *)slider
{
    double newSeekTime = (_progressSlider.value / 100.0) * [AudioPlayer ShowInstance].streamer.duration;
    [[AudioPlayer ShowInstance].streamer seekToTime:newSeekTime];
}

#pragma mark 文本框 设置歌曲链接

//设置歌曲链接的
- (void)CreatedownloadSourceField
{
    [AudioPlayer ShowInstance].downloadSourceField = [[[UITextField alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 10, 200, 80)] autorelease];
    [AudioPlayer ShowInstance].downloadSourceField.backgroundColor = [UIColor cyanColor];
    [AudioPlayer ShowInstance].downloadSourceField.text = _p.musicUrl;
    [[AudioPlayer ShowInstance].dbjtImageView addSubview:[AudioPlayer ShowInstance].downloadSourceField];
}


#pragma mark 点击直接播放
- (void)viewDidAppear:(BOOL)animated
{
    if ([_currentImageName isEqual:@"playbutton.png"])
    {
        [self createStreamer];
        [self buttonActionX:self.buttonX];
        [[AudioPlayer ShowInstance].downloadSourceField resignFirstResponder];
        [self setButtonImageNamed:@"loadingbutton.png"];
        [[AudioPlayer ShowInstance].streamer start];
    }
}

#pragma mark 播放按钮
//播放按钮
- (void)CreateButton
{
    
    self.button = [[[UIButton alloc] initWithFrame:CGRectMake(150, 320, 80, 80)] autorelease];
    self.button.alpha = 0.8;
    self.button.center = CGPointMake(kScreenWidth/2, kScreenHeight/3);
    [_button.layer setCornerRadius:60];
    [_button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button];
}

//播放按钮的点击方法
- (void)buttonPressed:(id)sender
{
    if ([_currentImageName isEqual:@"playbutton.png"])
    {
        [self buttonActionX:self.buttonX];
        [self createStreamer];
        [[AudioPlayer ShowInstance].downloadSourceField resignFirstResponder];
        [self setButtonImageNamed:@"loadingbutton.png"];
        [[AudioPlayer ShowInstance].streamer start];
        
    }
    else
    {
        [[AudioPlayer ShowInstance].streamer pause];
        [self setButtonImageNamed:@"playbutton.png"];
        [self.buttonX.layer removeAllAnimations];
    }
    
}


- (void)createStreamer
{
    if ([AudioPlayer ShowInstance].streamer)
    {
        return;
    }
    
    [self destroyStreamer];
    self.escapedValue = [AudioPlayer ShowInstance].downloadSourceField.text;
    
    NSURL *url = [NSURL URLWithString:self.escapedValue];
    [AudioPlayer ShowInstance].streamer = [[[AudioStreamer alloc] initWithURL:url] autorelease];
    
    _progressUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateProgress:) userInfo:nil repeats:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackStateChanged:) name:ASStatusChangedNotification object:[AudioPlayer ShowInstance].streamer];
}

- (void)destroyStreamer
{
    if ([AudioPlayer ShowInstance].streamer)
    {
        [[NSNotificationCenter defaultCenter]
         removeObserver:self
         name:ASStatusChangedNotification
         object:[AudioPlayer ShowInstance].streamer];
        [_progressUpdateTimer invalidate];
        _progressUpdateTimer = nil;
        
        [[AudioPlayer ShowInstance].streamer stop];
        [AudioPlayer ShowInstance].streamer = nil;
    }
}

- (void)playbackStateChanged:(NSNotification *)aNotification
{
    if ([[AudioPlayer ShowInstance].streamer isWaiting])
    {
        [self setButtonImageNamed:@"loadingbutton.png"];
    }
    else if ([[AudioPlayer ShowInstance].streamer isPlaying])
    {
        [self setButtonImageNamed:@"pausebutton.png"];
    }
    else if ([[AudioPlayer ShowInstance].streamer isIdle])
    {
        [self destroyStreamer];
        [self setButtonImageNamed:@"playbutton.png"];
    }
}

- (void)setButtonImageNamed:(NSString *)imageName
{
    
    if (!imageName)
    {
        imageName = @"playButton";
    }
    [self.currentImageName autorelease];
    self.currentImageName = [imageName retain];
    NSLog(@"%ld", _currentImageName.retainCount);
    UIImage *image = [UIImage imageNamed:imageName];
    [self.button.layer removeAllAnimations];
    [_button setImage:image forState:0];
    
    if ([imageName isEqual:@"loadingbutton.png"])
    {
        [self spinButton];
    }
}

- (void)spinButton
{
    [CATransaction begin];
    [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
    CGRect frame = [self.button frame];
    self.button.layer.anchorPoint = CGPointMake(0.5, 0.5);
    self.button.layer.position = CGPointMake(frame.origin.x + 0.5 * frame.size.width, frame.origin.y + 0.5 * frame.size.height);
    [CATransaction commit];
    
    [CATransaction begin];
    [CATransaction setValue:(id)kCFBooleanFalse forKey:kCATransactionDisableActions];
    [CATransaction setValue:[NSNumber numberWithFloat:2.0] forKey:kCATransactionAnimationDuration];
    CABasicAnimation *animation = [[CABasicAnimation new] autorelease];
    animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = [NSNumber numberWithFloat:0.0];
    animation.toValue = [NSNumber numberWithFloat:2 * M_PI];
    animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear];
    animation.delegate = self;
    [self.button.layer addAnimation:animation forKey:@"rotationAnimation"];
    [CATransaction commit];
}


#pragma mark 创建显示进度的Lable
- (void)createSliderPositionLeft
{
    
    _positionLabelLeft = [[[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(_progressSlider.frame) - 35.0 / 375 * kScreenWidth, CGRectGetMidY(_progressSlider.frame) - 4.0 / 667 * kScreenHeight, 40.0 / 375 * kScreenWidth, 12.0 / 667 * kScreenHeight)] autorelease];
    
    
    _positionLabelLeft.font = [UIFont fontWithName:@"Optima" size:12];
    
    _positionLabelLeft.textColor = [UIColor blackColor];
    [self.view addSubview:_positionLabelLeft];
    
}
- (void)createSliderPositionRight
{
    
    _positionLabelRight = [[[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_progressSlider.frame) + 12.0 / 375 * kScreenWidth, CGRectGetMidY(_progressSlider.frame) - 4.0 / 667 * kScreenHeight, 40.0 / 375 * kScreenWidth, 12.0 / 667 * kScreenHeight)] autorelease];
    
    _positionLabelRight.font = [UIFont fontWithName:@"Optima" size:12];
    _positionLabelRight.textColor = [UIColor blackColor];
    [self.view addSubview:_positionLabelRight];
    
}


- (void)updateProgress:(NSTimer *)updatedTimer
{
    
    if ([AudioPlayer ShowInstance].streamer.bitRate != 0.0)
    {
        double progress = [AudioPlayer ShowInstance].streamer.progress;
        double duration = [AudioPlayer ShowInstance].streamer.duration;
        if (duration > 0)
        {
            
            NSInteger b = (NSInteger) progress;
            _positionLabelLeft.text = [NSString stringWithFormat:@"%ld:%.2ld", b / 60, b % 60];
            progress -= 1;
            NSInteger a = duration - progress;
            [_positionLabelRight setText: [NSString stringWithFormat:@"%ld:%.2ld", a / 60, a % 60]];
            [_progressSlider setEnabled:YES];
            [_progressSlider setValue:100 *progress / duration];
        }
        else
        {
            [_progressSlider setEnabled:NO];
        }
    }
    else
    {
        //        _positionLabel.text = @"Time Played:";
    }
    
}

- (void)dealloc
{
    [_currentImageName release];
    [_tingid2 release];
    
    
    [super dealloc];
}
@end
